package com.example.rpcdemo.server.listener;

import com.example.rpcdemo.core.server.RpcServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class RpcServerStartListener implements ApplicationListener<ApplicationReadyEvent> {
    
    @Autowired
    private RpcServer rpcServer;
    
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            System.out.println("Starting RPC Server on port " + rpcServer.getPort());
            executorService.submit(() -> {
                try {
                    rpcServer.start();
                    System.out.println("RPC Server started successfully");
                } catch (Exception e) {
                    System.err.println("Failed to start RPC Server: " + e.getMessage());
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            System.err.println("Failed to submit RPC Server start task: " + e.getMessage());
            e.printStackTrace();
        }
    }
}